import datetime
from datetime import timedelta

from app.monitor_logs.handlers.service_handler import get_abnormal_service
from app.monitor_logs.handlers.url_handler import kibana6_log_app_url
from app.monitor_logs.handlers.notice_handler import abnormal_service
from app.monitor_logs.handlers.http_record_handler import MonitorLogHttpRecordHandler
from app.celery_task.models.celery_task import CeleryTask
from common.database import SessionLocal
from common.elastic import get_es, get_task_es
from core.celery import celery_app, TaskMonitor
from core.logger import logger


@celery_app.task(base=TaskMonitor, bind=True)
def monitor_logs_abnormal_application_notice(self, key="4b62c9fe-9cf1-40c3-be22-5d48323039f2", interval_min=5):
    now = datetime.datetime.now()
    cst_begin_time = (now - timedelta(minutes=interval_min)).strftime("%Y-%m-%d %H:%M:%S")
    cst_end_time = now.strftime("%Y-%m-%d %H:%M:%S")
    index = 'logstash-applog*'
    log_level = "ERROR"
    es = get_es()
    db = SessionLocal()
    items = get_abnormal_service(es_client=es, index=index, cst_begin_time=cst_begin_time, cst_end_time=cst_end_time, log_level=log_level,
                                 session=db)
    if items:
        for item in items:
            kibana_app_url = kibana6_log_app_url(schema="https", host="kibana.wolaidai.com", port=443, index_pattern_id='logstash-applog',
                                                 filter_fields_app=item['abnormal_server'], cst_begin_time=cst_begin_time,
                                                 cst_end_time=cst_end_time, filter_log_level=log_level,
                                                 prefix_route="/", exclude_keywords=item['exclude_keywords'])
            abnormal_service(key, item['abnormal_server'], item['cst_begin_time'], item['cst_end_time'], item['abnormal_server'],
                             item['exclude_k_abnormal_count'], item['character_log'], item['exclude_k_abnormal_count'], kibana_app_url, db)
    db.close()

@celery_app.task(base=TaskMonitor, bind=True)
def monitor_logs_abnormal_bigdata_notice(self, key="cde61185-2ed5-436e-b908-94187d64947f", interval_min=5):
    now = datetime.datetime.now()
    cst_begin_time = (now - timedelta(minutes=interval_min)).strftime("%Y-%m-%d %H:%M:%S")
    cst_end_time = now.strftime("%Y-%m-%d %H:%M:%S")
    index = 'logstash-cdh*'
    log_level = "ERROR"
    es = get_es()
    db = SessionLocal()
    items = get_abnormal_service(es_client=es, index=index, cst_begin_time=cst_begin_time, cst_end_time=cst_end_time, log_level=log_level,
                                 session=db)
    if items:
        for item in items:
            kibana_app_url = kibana6_log_app_url(schema="https", host="kibana.wolaidai.com", port=443,
                                                 index_pattern_id='3ca386d0-0345-11ed-b9bf-335225ac6780',
                                                 filter_fields_app=item['abnormal_server'], cst_begin_time=cst_begin_time,
                                                 cst_end_time=cst_end_time, filter_log_level=log_level,
                                                 prefix_route="/", exclude_keywords=item['exclude_keywords'])
            abnormal_service(key, item['abnormal_server'], item['cst_begin_time'], item['cst_end_time'], item['abnormal_server'],
                             item['exclude_k_abnormal_count'], item['character_log'], item['exclude_k_abnormal_count'], kibana_app_url, db)
    db.close()




@celery_app.task(base=TaskMonitor, bind=True)
def monitor_logs_http_record(self, interval_min=5):
    """
    更新http请求的记录信息异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    es_client = get_task_es()

    # 开始事件
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        monitor_log_http_record_handler = MonitorLogHttpRecordHandler()
        result = monitor_log_http_record_handler.task_update_from_es_handle(es_client, session, interval_min)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()
        es_client.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True




if __name__ == '__main__':
    # monitor_logs_abnormal_bigdata_notice()
    monitor_logs_http_record(interval_min=5)
